package com.panlin.daohang

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.appcompat.app.AppCompatActivity
import com.huawei.hms.location.FusedLocationProviderClient
import com.huawei.hms.location.LocationCallback
import com.huawei.hms.location.LocationResult
import com.huawei.hms.location.LocationServices
import com.huawei.hms.location.LocationSettingsRequest
import com.panlin.daohang.LocationUtils.LocationResultCallback
import com.panlin.daohang.PermissionUtils.PermissionCallback
import java.text.SimpleDateFormat


class MainActivity : AppCompatActivity() {

    private var mLocationRequest: com.huawei.hms.location.LocationRequest?=null

    // 定位交互接入对象
    private var fusedLocationProviderClient: FusedLocationProviderClient?=null
    private fun getPermission(){
        PermissionUtils.getInstance(this).checkLocationService(this){
            PermissionUtils.getInstance(this).checkAndRequestLocationPermission(this,object : PermissionCallback{
                override fun onGranted() {

                }

                override fun onDenied(deniedPermissions: List<String>) {

                }

                override fun onPermanentlyDenied(permanentlyDeniedPermissions: List<String>) {

                }

            })
        }
    }

    private lateinit var tvLocation: TextView

    private val simpleDateFormat by lazy {
        SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    }

    companion object{
        const val TAG = "MainActivity"
    }

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_article)
        getPermission()
        findViewById<Button>(R.id.btnHw).setOnClickListener {
            Thread{
                startLocation()
            }.start()
        }

        findViewById<Button>(R.id.btnSystem).setOnClickListener {
            LocationUtils.getInstance(this).startLocation(object : LocationResultCallback {
                override fun onLocationSuccess(latitude: Double, longitude: Double) {
                    // 定位成功
                    Log.d(TAG, "纬度:$latitude, 经度:$longitude")
                    runOnUiThread {
                        tvLocation.text = "系统定位Latitude: $latitude, longitude: $longitude"
                    }
                }

                override fun onLocationFailed(error: String) {
                    // 定位失败
                    Log.e(TAG, "定位失败: $error")
                    runOnUiThread {
                        tvLocation.text = "系统定位失败:$error"
                    }
                }
            })
        }

        tvLocation = findViewById<TextView>(R.id.tvLocation)

    }


    private fun checkLocationSettings(){
        val builder = LocationSettingsRequest.Builder()
        mLocationRequest = com.huawei.hms.location.LocationRequest()
        builder.addLocationRequest(mLocationRequest)
        val locationSettingsRequest = builder
            .build()
        LocationServices.getSettingsClient(this).checkLocationSettings(locationSettingsRequest)
            .addOnSuccessListener { locationSettingsResponse ->
                val locationSettingsStates = locationSettingsResponse.locationSettingsStates
                val stringBuilder = StringBuilder()
                stringBuilder.append("isLocationUsable=").append(locationSettingsStates.isLocationUsable)
                stringBuilder.append(",\nisHMSLocationUsable=")
                    .append(locationSettingsStates.isHMSLocationUsable)
                Log.i(TAG, "checkLocationSetting onComplete:$stringBuilder")
            }
            .addOnFailureListener { e ->
                Log.i(TAG, "checkLocationSetting onFailure:" + e.message)
            }


        val builder1 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val notificationChannel =
                NotificationChannel(packageName, "LOCATION", NotificationManager.IMPORTANCE_LOW)
            notificationManager.createNotificationChannel(notificationChannel)
            Notification.Builder(this, packageName)
        } else {
            Notification.Builder(this)
        }
        val mNotification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            builder1.build()
        } else {
            builder1.notification
        }
        // 实例化fusedLocationProviderClient对象
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
        fusedLocationProviderClient?.enableBackgroundLocation(1,mNotification)
    }


    private fun startLocation(){
        checkLocationSettings()
        fusedLocationProviderClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
            ?.addOnSuccessListener {
                Log.i(TAG, "startLocation success:")
            }
            ?.addOnFailureListener {
                Log.i(TAG, "startLocation fail:$it")
                runOnUiThread {
                    tvLocation.text = "华为定位失败: $it"
                }
            }
    }

    private val mLocationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult
        ) {
            if (locationResult != null) {
                locationResult.locations.forEachIndexed { index, location ->
                    Log.i(TAG, "Latitude  index:$index   ,latitude: ${location.latitude}, longitude: ${location.longitude}")
                    runOnUiThread {
                        tvLocation.text = "华为定位Latitude: ${location.latitude}, longitude: ${location.longitude}"
                    }
                }
            }
        }
    }


    private fun removeLocation(){
        fusedLocationProviderClient?.removeLocationUpdates(mLocationCallback)
            ?.addOnSuccessListener {
                Log.i(TAG, "removeLocation success:")
            }
            ?.addOnFailureListener {
                Log.i(TAG, "removeLocation error:$it")
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        removeLocation()
    }

}



